package org.real.guetshop.controller.user;

import io.swagger.v3.oas.annotations.Operation;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.real.guetshop.constant.StatusConstant;
import org.real.guetshop.pojo.dto.ProductQueryDTO;
import org.real.guetshop.pojo.entity.Product;
import org.real.guetshop.pojo.vo.ProductVO;
import org.real.guetshop.result.PageResult;
import org.real.guetshop.result.Result;
import org.real.guetshop.service.ProductService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("userProductController")
@Slf4j
@RequestMapping("/user/product")
public class ProductController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private ProductService productService;

    @GetMapping("/list")
    @Cacheable(value = "product", key = "'category_' + #categoryId")
    @Operation(summary = "根据分类id查询商品")
    public Result<List<ProductVO>> list(@RequestParam Integer categoryId) {

        //构建redis中的key，规则：product_分类id
        String key = "product::category_" + categoryId;

        //查询redis中是否存在商品数据
//        List<ProductVO> list = (List<ProductVO>) redisTemplate.opsForValue().get(key);
//        if (list != null) {
//            //如果存在直接返回,无需查询数据库
//            return Result.success(list);
//        }

        Product product = new Product();
        product.setCategoryId(categoryId);
        product.setStatus(StatusConstant.ENABLE);   //查询起售中的商品

        //如果不存在，查询mysql数据库，将查到的数据放入redis中
        List<ProductVO> list = productService.listByCategoryId(product);
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
    }

    /**
     * 商品分页查询
     * @param productQueryDTO
     * @return
     */
    @Operation(summary = "商品分页查询")
    @PostMapping("/page")
    public Result<PageResult> page(@RequestBody ProductQueryDTO productQueryDTO) {
        log.info("商品分页查询：{}",productQueryDTO);
        PageResult pageResult = productService.pageQueryByUser(productQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 获取热销商品
     * @return
     */
    @GetMapping("/hot")
    public Result<List<ProductVO>> hot() {
        log.info("获取热销商品......");
        List<ProductVO> list = productService.getHot();
        return Result.success(list);
    }

    /**
     * 用户商品收藏
     * @param productDTO
     * @return
     */
//    @PostMapping("/save")
//    public Result<ProductVO> save(@RequestBody ProductDTO productDTO) {
//        log.info("用户商品收藏{}",productDTO);
//
//    }
}
